package cn.lblbc.lib.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;


public class NestedHorizontalScrollView extends HorizontalScrollView {
    private float mLastFocusX;
    private boolean parentScroll;

    public NestedHorizontalScrollView(Context context) {
        this(context, null);
    }

    public NestedHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float focusX = event.getX();
        switch (event.getAction()) {
            case 0:
                this.mLastFocusX = focusX;
                if (this.parentScroll) {
                    this.parentScroll = false;
                    return false;
                }
                break;
            case 2:
                float scrollX = this.mLastFocusX - focusX;
                if (getScrollRange() != getScrollX() || scrollX <= 0.0f) {
                    this.mLastFocusX = focusX;
                    break;
                } else {
                    this.mLastFocusX = focusX;
                    this.parentScroll = true;
                    return false;
                }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
    }

    private int getScrollRange() {
        if (getChildCount() > 0) {
            return Math.max(0, getChildAt(0).getWidth() - ((getWidth() - getPaddingLeft()) - getPaddingRight()));
        }
        return 0;
    }
}